import 'package:flutter/material.dart';
import 'package:lib_uikit/dimen/gt_dimensions_v3.dart';
import 'package:lib_uikit/lib_uikit.dart';

///small30高度，xSmall24高度
enum GTSelectorSizeV3 { small, xSmall }

typedef void SelectorSingleClick(int index, bool isChecked);

///Selector 快筛组件
class GTSelectorV3 extends StatefulWidget {
  final List<GTSelectorModalV3> list;
  final int? crossAxisCount;

  //选中时是否展示右上角勾选icon，默认展示
  final bool? showCheck;

  //是否单选
  final bool? isSingle;

  //是否是流式布局(自适应宽度)，默认false平均等分布局
  final bool? isFlow;

  //单选回调（isSingle=true可以触发此回调）
  final SelectorSingleClick? onSingleClick;

  //多选回调（isSingle=false可以触发此回调）
  final ValueChanged<List<int>>? onMultipleClick;

  //默认选中下标
  final GTSelectorSizeV3? size;
  List<int>? selectIndexes;

  final bool? needClear;

  GTSelectorV3({
    super.key,
    required this.list,
    this.crossAxisCount = 2,
    this.showCheck,
    this.isSingle = true,
    this.isFlow = false,
    this.onSingleClick,
    this.onMultipleClick,
    this.selectIndexes,
    this.size = GTSelectorSizeV3.small,
    this.needClear,
  });

  @override
  State<StatefulWidget> createState() => _SelectorStateV3();
}

class _SelectorStateV3 extends State<GTSelectorV3> {
  double padding = 8;
  bool _isSingle = true;
  double height = 30, radius = 6, textSize = 13;
  IconData icon = GTIconFont.e8a6;
  bool isRTL = GTThemeProvider.instance.isRTL();

  @override
  void initState() {
    _isSingle = widget.isSingle ?? true;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    widget.selectIndexes ??= [];
    switch (widget.size ?? GTSelectorSizeV3.small) {
      case GTSelectorSizeV3.small:
        height = 30;
        radius = 6;
        textSize = 13;
        icon = isRTL ? GTIconFont.e8a5 : GTIconFont.e8a6;
        break;
      case GTSelectorSizeV3.xSmall:
        height = 24;
        radius = 4;
        textSize = 12;
        icon = isRTL ? GTIconFont.e89c : GTIconFont.e8a7;
        break;
    }

    double screenWidth = MediaQuery.of(context).size.width;
    double crossAxisSpacing = 8;
    int crossAxisCount = widget.crossAxisCount ?? 0;
    double totalSpacing = (crossAxisCount - 1) * crossAxisSpacing + padding * 2;
    double itemWidth = (screenWidth - totalSpacing) / crossAxisCount;
    double childAspectRatio = itemWidth / 32;
    if (widget.isFlow ?? false) {
      return Wrap(
        spacing: 8,
        runSpacing: 8,
        children: widget.list.asMap().entries.map((entry) {
          int index = entry.key;
          return selectorItem(index);
        }).toList(),
      );
    }
    return MediaQuery.removePadding(
      context: context,
      removeTop: true,
      removeBottom: true,
      child: GridView.count(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        crossAxisCount: crossAxisCount,
        crossAxisSpacing: crossAxisSpacing,
        mainAxisSpacing: 8,
        childAspectRatio: childAspectRatio,
        children: List.generate(widget.list.length, (index) {
          return AspectRatio(aspectRatio: 1 / childAspectRatio, child: selectorItem(index));
        }),
      ),
    );
  }

  Widget selectorItem(int index) {
    return GestureDetector(
      onTap: () {
        setState(() {
          if (_isSingle) {
            // 单选
            if (!widget.selectIndexes!.contains(index)) {
              widget.selectIndexes!.clear();
              widget.selectIndexes!.add(index);
              widget.onSingleClick?.call(index, true);
            } else {
              widget.selectIndexes!.clear();
              widget.onSingleClick?.call(index, false);
            }
          } else {
            // 多选
            if (widget.selectIndexes!.contains(index)) {
              widget.selectIndexes!.remove(index);
            } else {
              widget.selectIndexes!.add(index);
            }
            widget.onMultipleClick?.call(widget.selectIndexes!);
          }
        });
      },
      child: selectorItemWidget(index),
    );
  }

  Widget selectorItemWidget(int index) {
    bool isSelected = widget.selectIndexes!.contains(index);
    if (widget.needClear ?? false) {
      isSelected = false;
    }
    return IntrinsicWidth(
      child: Container(
        height: height,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(radius),
          border: Border.all(
            color: isSelected ? GTColorsV3.text9.color : GTColorsV3.divider5.color,
            width: GTDimensionsV3.strokeWidth,
          ),
        ),
        child: Stack(
          children: <Widget>[
            Center(
              child: Padding(
                padding: EdgeInsets.symmetric(horizontal: padding),
                child: Text(
                  widget.list[index].content,
                  style: gtTextStyleW500(
                      color: isSelected ? GTColorsV3.text9.color : GTColorsV3.text1.color, fontSize: textSize),
                ),
              ),
            ),
            if (isSelected && (widget.showCheck ?? true)) ...[
              Positioned(
                left: isRTL ? 0 : null,
                right: isRTL ? null : 0,
                top: 0,
                child: Icon(
                  icon,
                  size: 14,
                  color: GTColorsV3.icon9.color,
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }
}

class GTSelectorModalV3 {
  final String content;
  final int? id;

  GTSelectorModalV3({required this.content, this.id});
}
